import com.pbking.component.ComponentBase;
import com.pbking.util.Proxy;
import com.pbking.util.eventHandling.Event;

/**
 * @author Jason Crist
 */
class com.pbking.component.media.ComponentVideoPlayer extends ComponentBase 
{
	// VARIABLES //////////
	
	private var video:Video;
	private var netConnection:NetConnection;
	private var netStream:NetStream;
	private var duration:Number;
	
	// CONSTRUCTION //////////
	
	function ComponentVideoPlayer()
	{
		netConnection = new NetConnection();
		netConnection.connect(null);
		
		netStream = new NetStream(netConnection);
				
		netStream.onMetaData = Proxy.create(this, onMetaData);
		netStream.onStatus = Proxy.create(this, onStatus);
		
		video.attachVideo(netStream);
		this.attachAudio(netStream);
	}
	
	// PUBLIC FUNCTIONS //////////
	
	public function loadVideo(videoURL:String):Void
	{
		netStream.play(videoURL);
		netStream.seek(0);
		netStream.pause(true);
	}

	public function playVideo():Void
	{
		netStream.seek(0);
		netStream.pause(false);
	}
	
	public function stopVideo():Void
	{
		netStream.close();
	}
	
	public function pauseVideo():Void
	{
		netStream.pause(false);
	}
	
	public function unpauseVideo():Void
	{
		netStream.pause(true);
	}
	
	// PRIVATE FUNCTIONS //////////

	private function onMetaData(infoObject):Void
	{
		duration = infoObject.duration;
		onEnterFrame = checkForDone;
	}	
	
	private function checkForDone():Void
	{
		if(netStream.time >= duration-.25)
		{
			dispatch(new Event("movieDone", this));
		}
	}
	
	private function onStatus(infoObject:Object):Void
	{
		if(infoObject.level == "error")
		{
			switch(infoObject.code)
			{
				case "NetStream.Play.StreamNotFound":
					dispatch(new Event("StreamNotFound", this, infoObject));
					break;
					
				case "NetStream.Seek.InvalidTime":
					dispatch(new Event("InvalidTime", this, infoObject));
					break;
			}		
		}
		
		else if(infoObject.level = "status")
		{
			switch(infoObject.code)
			{
				case "NetStream.Buffer.Empty":
					onBufferEmpty();
					dispatch(new Event("BufferEmpty", this, infoObject));
					break;
					
				case "NetStream.Buffer.Full":
					onBufferFull();
					dispatch(new Event("BufferFull", this, infoObject));
					break;
					
				case "NetStream.Buffer.Flush":
					onBufferFull();
					dispatch(new Event("BufferFlush", this, infoObject));
					break;
					
				case "NetStream.Play.Start":
					onPlayStart();
					dispatch(new Event("Start", this, infoObject));
					break;
					
				case "NetStream.Play.Stop":
					onPlayStop();
					dispatch(new Event("Stop", this, infoObject));
					break;
				
				case "NetStream.Seek.Notify":
					onSeekNotify();
					dispatch(new Event("SeekNotify", this, infoObject));
					break;
					
			}
		}
	}
	
	private function onBufferEmpty(){}
	private function onBufferFull(){}
	private function onPlayStart(){}
	private function onPlayStop(){}
	private function onSeekNotify(){}

}